package com.oneday.nuo.base.tactics.token.impl;

import com.oneday.nuo.base.common.RedisUtil;
import com.oneday.nuo.base.config.CurrentUser;
import com.oneday.nuo.base.exception.LoginException;
import com.oneday.nuo.base.security.jwt.JwtUtil;
import com.oneday.nuo.base.security.user.NuoUser;
import com.oneday.nuo.base.tactics.token.TokenTactics;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component("tokenNotStatus")
@Slf4j
public class TokenNotStatus implements TokenTactics {

    @Value("${token.time-out}")
    private Long timeOut;
    @Value("${token.tokenSecret}")
    private String tokenSecret;

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public NuoUser setToken(NuoUser user) {
        log.info("无状态模式");
        //生成token
        String token = JwtUtil.sign(user, tokenSecret);
        user.setToken(token);
        redisUtil.set("user:"+user.getUsername(),user,timeOut);
      return user;
    }

    @Override
    public void verify(String token) {
        //是否通过
        boolean isPass = JwtUtil.verity(token, tokenSecret);
        if(!isPass){
            throw new LoginException("token已失效");
        }

    }

    @Override
    public NuoUser setUser(NuoUser user) {
        String userName = JwtUtil.getUserName(user.getToken());
        if(userName == null){
            throw new LoginException("token格式不正确");
        }
         user  = (NuoUser) redisUtil.get("user:" + userName);
        if(user == null){
            throw new LoginException("用户未认证");
        }else{
            redisUtil.expireSeconds("user:"+userName,timeOut);
        }
        return user;
    }

    @Override
    public void exitLogin(NuoUser user) {
        String userName = JwtUtil.getUserName(user.getToken());
        redisUtil.del("user:"+ userName);
    }
}
